<template>
  <div class="spider-container">
    <el-card class="spider-main" @click.native="toDetails" :body-style="{ padding: '0px' }">
      <el-image
          v-if="spider.imgUrl !== null"
          :src="spider.imgUrl"
          fit="cover"></el-image>
<!--      <span-->
<!--          v-else-->
<!--          class="spider-main-font">-->
<!--        {{ spider.spiderName | spiderDivBack }}-->
<!--      </span>-->
      <el-image
          v-else
          src="http://www.jxtz.net/static/home/images/logo.png"
          fit="cover"></el-image>
    </el-card>
    <span class="spider-font">{{ spider.spiderName }}</span>
    <el-dialog :title="spider.spiderName" :append-to-body="true" :visible.sync="spiderDetailsDiaLog" @close="dialogCloseHandle">
      <el-tabs v-model="activeName" @tab-click="refreshTab">
        <el-tab-pane label="开始爬取" name="first">
<!--          <el-tooltip class="item" effect="dark" content="实时抓取。爬取成功率：低；造成服务器攻击风险：高" placement="top-start">-->
<!--            <el-button type="primary" @click="realSpider">实时爬取</el-button>-->
<!--          </el-tooltip>-->

          <el-tooltip class="item" effect="dark" content="当晚24时开始爬取。爬取成功率：高；造成服务器攻击风险：低" placement="top-start">
            <el-button type="text" @click="pushOrder">预约爬取</el-button>
          </el-tooltip>

          <el-divider></el-divider>
          <el-table :data="executeList">
            <el-table-column label="爬虫名" prop="spiderName"/>
            <el-table-column label="预约用户" prop="userId"/>
            <el-table-column label="预约时间" prop="createTime" :formatter="timeFormatter"/>
            <el-table-column label="是否执行" prop="execute" :formatter="executeFormatter"/>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="text" @click="removeExecute(scope.row.id)">取消预约</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="历史爬取" name="second">
          <el-table :data="historyList" v-loading="downloadButtonLoading">
            <el-table-column label="爬取日期" prop="createTime" :formatter="timeFormatter"/>
            <el-table-column label="爬取总量" prop="count" />
            <el-table-column label="操作" >
              <template slot-scope="scope">
                <el-button type="text" @click="excelDownload(scope.row.id)">导出</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[sizePage, sizePage * 2, sizePage * 4, sizePage * 6]"
              :page-size="sizePage"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalPage">
          </el-pagination>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script>
import {
  pushOrder,
  getExecuteList,
  deletedSpider,
  getOverExecuteList,
  excelSpiderExecute,
  realTimeSpider
} from "@/api/Spider";
import Moment from 'moment'
export default {
  name: "card",
  props: {
    spider: {
      type: Object
    }
  },
  data(){
    return{
      currentPage: 1,
      sizePage: 10,
      totalPage: 0,

      spiderDetailsDiaLog: false,
      downloadButtonLoading: false,
      activeName: 'first',

      executeList: [],
      historyList: []
    }
  },
  filters: {
    spiderDivBack(val){
      return val.slice(0, 1)
    }
  },

  created() {

  },

  methods: {
    handleSizeChange(val) {
      this.sizePage = val
    },

    handleCurrentChange(val) {
      this.currentPage = val
    },

    toDetails() {
      this.spiderDetailsDiaLog = true
      this.getExecute()
    },

    dialogCloseHandle() {
      this.spiderDetailsDiaLog = false
      this.activeName = 'first'
    },

    getExecute() {
      getExecuteList(this.spider.spiderCode).then(res => {
        this.executeList = res.data.data.executeList
      })
    },

    pushOrder() {
      var item = sessionStorage.getItem('userInfo');
      var parse = JSON.parse(item);
      var id = parse.id;
      pushOrder({
        spiderName: this.spider.spiderName,
        spiderCode: this.spider.spiderCode,
        userId: id,
        execute: false
      }).then(res => {
        const data = res.data;
        if (data.code === 50000) {
          this.$message.error(data.message)
        }else {
          this.$message.success(data.message)
        }
        this.getExecute()
      })
    },

    timeFormatter(row, column, cellValue, index) {
      const date = new Date(cellValue * 1000);
      return Moment(date).format('YYYY-MM-DD HH:mm:ss')
    },

    executeFormatter(row, column, cellValue, index) {
      return cellValue === false ? '未执行':'已执行'
    },

    refreshTab(tab, event) {
      switch (tab.name) {
        case 'first':
          this.getExecute()
          break
        case 'second':
          this.getOverExecuteSpider()
          break
        default:

      }
    },

    getOverExecuteSpider() {
      getOverExecuteList(this.spider.spiderCode).then(res => {
        this.historyList = res.data.data.overExecute
      })
    },

    removeExecute(id) {
      deletedSpider(id).then(res => {
        const data = res.data;
        if (data.code === 50000) {
          this.$message.error(data.message)
        }else {
          this.$message.success(data.message)
        }
        this.getExecute()
      })
    },

    excelDownload(id) {
      this.downloadButtonLoading = true
      excelSpiderExecute(id, this.spider.spiderCode).then(res => {
        let data = res.data;
        let url = window.URL.createObjectURL(new Blob([data]));
        let link = document.createElement('a');
        link.style.display = 'none';
        link.href = url;
        const s = Moment(new Date().getTime()).format('YYYY-MM-DD');
        link.setAttribute('download', this.spider.spiderName + '-' + s + '.xlsx');
        document.body.appendChild(link);
        link.click()
        this.downloadButtonLoading = false
      })
    },

    realSpider() {
      var item = sessionStorage.getItem('userInfo');
      var parse = JSON.parse(item);
      var id = parse.id;
      const spiderDown = {
        spiderName: this.spider.spiderName,
        spiderCode: this.spider.spiderCode,
        userId: id
      }

      realTimeSpider(spiderDown).then(res => {
        const data1 = res.data;
        data1.code === 50000 ? this.$message.error(data1.message):this.$message.success(data1.message)
      })
    }
  }
}
</script>

<style scoped>

.spider-container {
  /*border: 1px solid black;*/
  float: left;
}

.spider-main{
  width: 100px;
  height: 100px;
  margin: 0 auto;
  border-radius: 10px;
  cursor: pointer;
}

.spider-font {
  font: 12px/1.5 Tahoma,Helvetica,Arial,'Apple Braille',sans-serif;
  font-weight: bolder;
}

.spider-main-font {
  font-family: "Apple Braille", Arial,sans-serif;
  color: black;
  font-weight: bolder;
  font-size: 55px;
}
</style>
